//
//  LoginViewModel.m
//  ObjcGoNew
//
//  Created by 邢伟新 on 2021/4/21.
//

#import "LoginViewModel.h"
#import <ReactiveObjC/ReactiveObjC.h>
#import "NSString+judge.h"
#import "AuthServer.h"

@implementation LoginViewModel
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self bindSomething];
        
    }
    return self;
}

-(void)bindSomething{
    
    @weakify(self);
    
    RAC(self,aUrlString) = [[RACObserve(self, userName) map:^id _Nullable(id  _Nullable value) {
        return [NSString wx_isValidMobile:value] ? @"url" : @"";
    }] distinctUntilChanged]; //忽略重复信号
    
    self.validLoginSignal = [[RACSignal combineLatest:@[RACObserve(self, userName),RACObserve(self, password)] reduce:^(NSString *userName,NSString *password){
        
        return @(userName.length > 0 && password.length > 6);
        
    }] distinctUntilChanged];
    
    
    self.loginCommand = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        
        @strongify(self);
        if (![NSString wx_isValidMobile:self.userName]) {
            return [RACSignal error:[NSError errorWithDomain:@"输入手机号不正确" code:100 userInfo:nil]];
        }else if(self.password.length < 6){
            
            return [RACSignal error:[NSError errorWithDomain:@"输入的密码小于6位" code:101 userInfo:nil]];
        }
        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [AuthServer loginUserName:@"cgac\\xing_weixin" passWord:@"111111" Success:^(NSDictionary * _Nonnull resultDic) {
                    
                    [subscriber sendNext:resultDic];
                    [subscriber sendCompleted];
                    
                    
                } failure:^(NSError * _Nonnull error) {
                    
                    [subscriber sendError:error];
                    
                    
                } state:^(NSString * _Nonnull reqestState) {
                    
                }];
            });
            
            return nil;
        }];
        
        
        
    }];
    
    
}

@end
